package com.mtf.io;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author matengfei
 * @Date 2024/5/27 15:50
 * @PackageName:com.mtf.io
 * @ClassName: BlockingService
 * @Description: BIO：同步阻塞IO
 * @Version 1.0
 */
@Slf4j
public class BlockingService {
    public static void main(String[] args) throws IOException {
        // 创建可缓存的线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 监听特定的端口，等待客户端连接
        ServerSocket serverSocket = new ServerSocket(9000);
        while (true) {
            log.info("正在监听...");
            //  阻塞监听客户端的请求，监听成功返回Socket对象
            final Socket accept = serverSocket.accept();
            log.info("成功建立连接，并分配给线程 {} 执行", Thread.currentThread().getName());
            executorService.execute(() -> {
                try {
                    handle(accept);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private static void handle(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        //  get input stream by socket
        try (InputStream inputStream = socket.getInputStream()) {
            // loop read the data from client
            while (true) {
                int read = inputStream.read(bytes);
                if (-1 != read) {
                    String clientMessage = new String(bytes, 0, read);
                    log.info("===== thread <{}> get client message: {}", Thread.currentThread().getName(), clientMessage);
                } else {
                    break;
                }
            }
        }
    }
}
